<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null
    }
  },
  created() {

  },
  mounted() {
    this.initChart()
    if (this.autoResize) {
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
    }

    // 监听侧边栏的变化
    const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm.addEventListener('transitionend', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.__resizeHanlder)
    }

    const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm.removeEventListener('transitionend', this.__resizeHanlder)

    this.chart.dispose()
    this.chart = null
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  computed: {

  },

  methods: {
    setOptions({ subjectArr, scoreArr, student} = {}) {
      this.chart.setOption({
        title: {
          text: '学生成绩分析雷达图'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['张三']
        },
        radar: {
          name: {
            textStyle: {
              color: '#fff',
              backgroundColor: '#999',
              borderRadius: 3,
              padding: [3, 5]
            }
          },
          indicator: [
            { text: '语文', max: 1 },
            { text: '数学', max: 1 },
            { text: '英语', max: 1 },
            { text: '物理', max: 1 },
            { text: '化学', max: 1 }
          ],
          center: ['75%', '50%'],
          radius: 120
        },
        series: [{
          name: '成绩单',
          type: 'radar',
          areaStyle: {normal: {}},
          data: [{
            value: [0.92, 0.85, 0.50, 0.45, 0.78, 0.35],
            name: '张三',
            label: {
            show: true,
            formatter: function(params) {
                return params.value;
            }
            }
          }]
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    }
  }
}
</script>


option = {

};